# -*- coding: utf-8 -*-
import wx
import re
import os
import time
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor

from image_to_ocr import easyocr_nested_folders
from wechat_code_retrieval import init
import easyocr
from functools import partial

from pathlib import Path

# ocr_engine = PaddleOCR(use_angle_cls=False, lang="ch", cls_thresh=1, use_gpu=False)
ocr_engine = easyocr.Reader(['ch_sim', 'en'])



class ComboPanel(wx.Panel):
    def _style_button(self, button):
        button.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))  # 设置字体
        button.SetBackgroundColour(wx.Colour(200, 200, 200))  # 设置背景色
        button.SetForegroundColour(wx.Colour(33, 33, 33))  # 设置文字颜色
        button.SetSize((150, 40))  # 设置按钮大小
        button.SetCursor(wx.Cursor(wx.CURSOR_HAND))  # 鼠标悬浮时显示手形光标
        button.SetMinSize((150, 40))  # 设置最小按钮大小

    def _style_checkbox(self, checkbox):
        checkbox.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))  # 设置字体
        checkbox.SetForegroundColour(wx.Colour(0, 0, 0))  # 设置文本颜色
        checkbox.SetBackgroundColour(wx.Colour(255, 255, 255))  # 设置背景色
        checkbox.SetValue(False)  # 默认未选中
        checkbox.SetSize((200, 40))  # 设置复选框大小
        checkbox.SetCursor(wx.Cursor(wx.CURSOR_HAND))  # 鼠标悬浮时显示手形光标

        # 改善复选框的边框和外观
        checkbox.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)  # 更紧凑的风格

    def __init__(self, parent, title):
        super().__init__(parent)

        # 创建一个水平的 BoxSizer 来排列按钮和复选框
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        # 创建一个垂直的 BoxSizer 来排列按钮
        vbox_left = wx.BoxSizer(wx.VERTICAL)
        self.button = wx.Button(self, label=title)
        self._style_button(self.button)
        vbox_left.Add(self.button, 0, wx.ALL | wx.CENTER, 5)

        # 创建一个垂直的 BoxSizer 来排列复选框
        vbox_right = wx.BoxSizer(wx.VERTICAL)
        self.checkbox = wx.CheckBox(self, label="开启私信回复")
        self._style_checkbox(self.checkbox)
        vbox_right.Add(self.checkbox, 0, wx.ALL | wx.CENTER, 5)

        # 将左右 BoxSizer 添加到水平布局中
        hbox.Add(vbox_left, 1, wx.EXPAND | wx.ALL, 5)  # 左侧占满空间
        hbox.Add(vbox_right, 0, wx.ALL, 5)             # 右侧按内容大小显示

        # 设置面板的布局
        self.SetSizerAndFit(hbox)  # 使用 SetSizerAndFit 来适应窗口的内容大小

        # 绑定复选框事件
        self.checkbox.Bind(wx.EVT_CHECKBOX, self.on_checkbox_change)

    def on_checkbox_change(self, event):
        # 获取复选框的当前选中状态
        if self.checkbox.GetValue():
            # 选中时修改复选框的背景色
            self.checkbox.SetForegroundColour(wx.Colour(255, 255, 255))  # 设置文本颜色
            self.checkbox.SetBackgroundColour(wx.Colour(0, 122, 255))  # 蓝色

        else:
            # 未选中时恢复默认背景色
            self.checkbox.SetForegroundColour(wx.Colour(0, 0, 0))  # 设置文本颜色
            self.checkbox.SetBackgroundColour(wx.Colour(255, 255, 255))  # 白色

        # 重新绘制面板以应用背景色的改变
        self.checkbox.Refresh()


class MyFrame(wx.Frame):
    def getIp(self):
        ip_str = Path( r"C:\device_ip.txt").read_text(encoding='utf-8')
        return [ip.strip().strip("'") for ip in ip_str.split(',')]
    def __init__(self):
        super().__init__(None, title="IMAI.WORK数据采集", size=(1920, 800))

        # 初始化线程池（全局复用）
        self.executor = ThreadPoolExecutor(max_workers=10)

        self.deviceIp = self.getIp() #['10.88.80.91','10.88.80.171','10.88.80.106', '10.88.80.166', '10.88.81.134','10.88.81.82','10.88.80.245', '10.88.81.99', '10.88.80.94', '10.88.80.174'] #self.getIp() #
        self.SetIcon(wx.Icon("icon.ico", wx.BITMAP_TYPE_ICO))  # 请替换为图标文件路径

        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.deviceIndex = 0
        self.linkDict = {}

        # 创建一个水平 BoxSizer 来布局左侧和右侧部分
        main_sizer = wx.BoxSizer(wx.HORIZONTAL)

        # 左侧部分：用于数据添加
        left_sizer = wx.BoxSizer(wx.VERTICAL)

        # 创建 ListBox 来显示列表项
        self.listbox = wx.ListBox(self.panel, size=(300, 400), pos=(20, 20))
        left_sizer.Add(self.listbox, flag=wx.EXPAND | wx.ALL, border=10)

        # 创建文本框，用于输入关键字
        self.keyword_input = wx.TextCtrl(self.panel, size=(120, 30))
        self.keyword_input.SetHint("搜索关键字")
        left_sizer.Add(self.keyword_input, flag=wx.EXPAND | wx.ALL, border=10)

        # deviceIp = ['10.88.80.91','10.88.80.245','10.88.80.171','10.88.81.97']
        # 创建下拉选择框，用于选择设备IP
        self.device_combobox = wx.ComboBox(
            self.panel,
            size=(170, 30),
            choices=["设备 1", "设备 2", "设备 3", "设备 4", "设备 5", "设备 6", "设备 7", "设备 8", "设备 9", "设备 10"],  # 默认选项
            style=wx.CB_DROPDOWN
        )
        self.device_combobox.SetHint("选择设备")  # 设置提示文本
        left_sizer.Add(self.device_combobox, flag=wx.EXPAND | wx.ALL, border=10)

        # 创建按钮，用于添加项到 ListBox
        self.add_button = wx.Button(self.panel, label="添加到列表")
        self._style_button(self.add_button)  # 美化按钮
        self.add_button.Bind(wx.EVT_BUTTON, self.on_add_item)
        left_sizer.Add(self.add_button, flag=wx.EXPAND | wx.ALL, border=10)

        self.clear_button = wx.Button(self.panel, label="清除数据")
        self._style_button(self.clear_button)  # 美化按钮
        self.clear_button.Bind(wx.EVT_BUTTON, self.on_clear_button)
        left_sizer.Add(self.clear_button, flag=wx.EXPAND | wx.ALL, border=10)

        now = datetime.now()
        self.formatted_date = now.strftime("%Y_%m_%d")
        self.date_input = wx.TextCtrl(self.panel, size=(120, 30))
        self.date_input.SetHint("输入日期文件名，例："+self.formatted_date)
        left_sizer.Add(self.date_input, flag=wx.EXPAND | wx.ALL, border=10)

        self.process_button = wx.Button(self.panel, label="生成文档数据")
        self._style_button(self.process_button)  # 美化按钮
        self.process_button.Bind(wx.EVT_BUTTON, self.on_process_button)
        left_sizer.Add(self.process_button, flag=wx.EXPAND | wx.ALL, border=10)

        # 右侧部分：采集次数和开始按钮
        # 右侧部分：采集次数和开始按钮
        right_sizer = wx.BoxSizer(wx.VERTICAL)

        # 字体样式
        self.font_style = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)

        # 创建网格布局来放置采集次数和按钮
        grid_sizer = wx.GridBagSizer(8, 2)  # 5 行 2 列

        # 标签
        label = wx.StaticText(self.panel, label="采集次数：")
        label.SetFont(self.font_style)
        grid_sizer.Add(label, pos=(0, 0), flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=10)

        # 输入框，设置宽度约等于 Tkinter 的 width=25
        self.loop_count_entry = wx.TextCtrl(self.panel, size=(-1, -1))
        self.loop_count_entry.SetFont(self.font_style)
        self.loop_count_entry.SetValue("200")  # 设置默认值
        grid_sizer.Add(self.loop_count_entry, pos=(0, 1), flag=wx.EXPAND | wx.ALL, border=10)

        private_message_name = wx.StaticText(self.panel, label="私信话术：", size=(-1, -1))
        private_message_name.SetFont(self.font_style)
        grid_sizer.Add(private_message_name, pos=(1, 0), flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
                       border=10)

        self.private_message = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE, size=(-1, 180))
        self.private_message.SetFont(self.font_style)
        self.private_message.SetValue(
            "你好\n我想了解一下")  # 设置默认值

        grid_sizer.Add(self.private_message, pos=(1, 1), flag=wx.EXPAND | wx.ALL, border=10)
        self.device_buttons = {}
        # 动态创建按钮并绑定事件
        for i in range(len(self.deviceIp)):

            button_label = f"设备{i + 1}开始采集"
            combo_panel = ComboPanel(self.panel,button_label)

            # combo_panel.button.Bind(wx.EVT_BUTTON,
            #                         lambda event, index=i: self.on_button_click(combo_panel,index))  # 使用 lambda 函数传递索引

            combo_panel.button.Bind(wx.EVT_BUTTON, partial(self.on_button_click, combo_panel, i))

            # 将按钮添加到网格中
            row = i // 2  # 每行两个按钮
            col = i % 2  # 交替排列按钮
            grid_sizer.Add(combo_panel, pos=(row + 2, col), flag=wx.EXPAND | wx.ALL, border=10)

            # 存储按钮到字典
            self.device_buttons[i] = combo_panel.button


        # 让第二列水平扩展填充
        grid_sizer.AddGrowableCol(0)
        grid_sizer.AddGrowableCol(1)

        # 设置网格尺寸调整
        right_sizer.Add(grid_sizer, flag=wx.EXPAND | wx.ALL, border=10)

        # 运行日志区域
        log_sizer = wx.BoxSizer(wx.VERTICAL)

        self.log_title = wx.StaticText(self.panel, label="运行日志")
        self.log_title.SetFont(self.font_style)
        log_sizer.Add(self.log_title, flag=wx.EXPAND | wx.ALL, border=1)

        # 创建 ListBox 来显示列表项
        self.logbox = wx.ListBox(self.panel, size=(300, 700), pos=(20, 20))
        log_sizer.Add(self.logbox, flag=wx.EXPAND | wx.ALL, border=10)


        # 将左右部分的 Sizer 添加到主 Sizer 中
        main_sizer.Add(left_sizer, 2, flag=wx.EXPAND | wx.ALL, border=10)
        main_sizer.Add(right_sizer, 3, flag=wx.EXPAND | wx.ALL, border=10)
        main_sizer.Add(log_sizer, 2, wx.EXPAND | wx.ALL, 5)

        # 设置主布局
        self.panel.SetSizer(main_sizer)

        self.Centre()
        self.Show(True)

    def _style_button(self, button):
        button.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))  # 设置字体
        button.SetBackgroundColour(wx.Colour(200, 200, 200))  # 设置背景色
        button.SetForegroundColour(wx.Colour(33, 33, 33))  # 设置文字颜色
        button.SetSize((150, 40))  # 设置按钮大小
        button.SetCursor(wx.Cursor(wx.CURSOR_HAND))  # 鼠标悬浮时显示手形光标
        button.SetMinSize((150, 40))  # 设置最小按钮大小

    def on_clear_button(self, event):
        self.deviceIndex = 0
        self.linkDict = {}
        self.listbox.Clear()

    def on_process_button(self,event):

        date = self.date_input.GetValue().strip()
        print("on_process_button"+date)
        if len(date)>0:
            print("on_process_button1" + date)
            self.formatted_date = date
        relative_path = os.path.join(self.formatted_date)
        self.executor.submit(
            easyocr_nested_folders,
            relative_path,
            self.formatted_date,
            self.add_log
        )


    def on_add_item(self, event):
        # 获取并检查关键字
        keyword = self.keyword_input.GetValue().strip()
        if not keyword:
            wx.MessageBox("关键字不能为空！", "输入错误", wx.ICON_ERROR)
            return

        selected_idx = self.device_combobox.GetSelection()

        if selected_idx == wx.NOT_FOUND:
            wx.MessageBox("请先选择设备！", "提示", wx.OK | wx.ICON_INFORMATION)
            return

        device = self.deviceIp[selected_idx]

        self.linkDict[selected_idx] = [keyword, device]

        if keyword and device:
            item = f"设备{(selected_idx + 1)}：{keyword} - {device}"
            self.listbox.Append(item)
            self.keyword_input.SetValue("")
            self.device_combobox.SetSelection(wx.NOT_FOUND)

    def _start_device_task(self, device_index,checkbox_value):
        """通用设备任务启动方法（使用字典存储设备配置）"""
        # 验证输入
        loop_count = self.loop_count_entry.GetValue().strip()
        try:
            loopCount = int(loop_count)
        except ValueError:
            wx.MessageBox("循环次数必须是一个整数！", "错误", wx.OK | wx.ICON_ERROR)
            return

        private_message_info = self.private_message.GetValue().strip()
        private_message_List = private_message_info.split('\n')
        print(private_message_List)

        # 检查设备是否存在（字典方式）
        if device_index not in self.linkDict:  # 直接判断 key 是否存在
            wx.MessageBox(f"设备{(device_index + 1)}配置不存在", "错误", wx.OK | wx.ICON_ERROR)
            return

        # 更新UI
        btn = self.device_buttons[device_index]
        btn.SetLabel("采集中...")
        btn.Disable()
        btn.Refresh()

        # 从字典获取数据
        keyword_str, device_ip = self.linkDict[device_index]  # 解包赋值
        keywords = keyword_str.split("、")  # 分割关键字

        # 提交任务
        future = self.executor.submit(
            self._run_device_task,
            keywords,
            device_ip,
            loopCount,
            private_message_List,
            checkbox_value
        )
        future.add_done_callback(lambda f: self._on_task_done(f, device_index))

    def _run_device_task(self, keywords, device, count, private_message_List,checkbox_value):
        print("_run_device_task==="+str(checkbox_value))
        """实际执行采集任务"""
        try:
            init(keywords, device, count, ocr_engine, private_message_List,checkbox_value,self.add_log)
        except Exception as e:
            return (False, str(e))
        return (True, None)

    def add_log(self, message):
        """通过回调函数将日志添加到 ListBox"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S:%f")[:-3]  # 获取当前时间并格式化
        log_message = f"[ {current_time} ] :  {message}"  # 将时间和日志消息合并
        print('add_log',message)
        self.logbox.Insert(log_message, 0)

    def _on_task_done(self, future, device_index):
        """任务完成回调"""
        success, error = future.result()
        btn = self.device_buttons[device_index]

        wx.CallAfter(btn.SetLabel, f"设备{(device_index + 1)}开始采集")
        wx.CallAfter(btn.Enable)
        wx.CallAfter(btn.Refresh)

        if not success:
            wx.CallAfter(wx.MessageBox, f"设备{(device_index + 1)}采集失败:\n{error}",
                         "错误", wx.OK | wx.ICON_ERROR)

    # 按钮事件绑定
    def on_button_click(self, combo_panel, index, event):
        # 获取 ComboPanel 中复选框的状态
        checkbox_value = combo_panel.checkbox.GetValue()
        print(f"设备{index + 1}开始采集的按钮被点击")
        print(f"设备{index + 1}的复选框状态: {checkbox_value}")
        self._start_device_task(index,checkbox_value)

    def show_error_message(self, message):
        wx.MessageBox(message, "连接失败", wx.ICON_ERROR)


if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()
